package com.xx.permission.utils;

import com.xx.permission.config.CacheData;
import com.xx.permission.entity.result.DataPermission;
import com.xx.permission.entity.result.RoleDataPermission;
import com.xx.permission.entity.result.UserDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author aqi
 * @since 2023/5/17 14:20
 */
@Slf4j
public class UserUtils {

    public static UserDTO currentUser;

    /**
     * 获取当前用户信息
     * @return 用户信息
     */
    public static UserDTO getCurrentUserInfo() {
        return currentUser;
    }

    /**
     * 模拟登录之后往session或者redis中存储用户信息的过程
     * @param user 用户信息
     */
    public static void setCurrentUser(UserDTO user) {
        UserUtils.currentUser = user;
    }

    /**
     * 获取用户权限信息
     * @return 用户权限信息
     */
    public static Map<String, List<DataPermission>> getUserPermission() {
        // 获取当前用户信息
        UserDTO currentUserInfo = UserUtils.getCurrentUserInfo();
        // 获取当前用户角色下的所有接口数据权限集合
        List<RoleDataPermission> roleDataPermissionList = CacheData.ROLE_DATA_PERMISSION_MAP.get(currentUserInfo.getRoleId());
        // key:uri(接口地址),value:DataPermission(数据权限)
        return roleDataPermissionList.stream().collect(Collectors.toMap(RoleDataPermission::getUri, RoleDataPermission::getDataPermissionList));
    }

    /**
     * 获取本次请求的uri
     * @return uri
     */
    public static String getUri() {
        // 获取此次请求的uri
        String uri = "";
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if (null != requestAttributes) {
            HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
            uri = request.getRequestURI();
        }
        return uri;
    }
}
